package com.keepmoving.web;

import com.keepmoving.po.Login;
import com.keepmoving.po.Role;
import com.keepmoving.po.User;
import com.keepmoving.service.LoginService;
import com.keepmoving.service.RoleService;
import com.keepmoving.service.UserService;
import com.keepmoving.util.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 * @author zxd
 */
@Controller
public class UserConrtoller {
    @Resource
    UserService userService;
    @Resource
    LoginService loginService;
    @Resource
    RoleService roleService;

    //进入简单注册页面
    @RequestMapping("/toeasyregist")
    public String toregist(Model model){
        List<Role> roles=roleService.findAll();
        model.addAttribute("roles",roles);
        return "easyregist";
    }
    //进入注册页面
    @RequestMapping("/addlogin")
    public String addlogin(@ModelAttribute Login login){
        int lid= loginService.addLogin(login);
        User user=new User();
        user.setUserName(login.getlName());
        user.setPass(login.getlPass());
        user.setlId(lid);
        userService.addUser(user);
        return "redirect:/tologin1.action?lId="+lid;
    }

    //进入登录页面
    @RequestMapping("/tologin1")
    public String tologin(String lId,Model model){
        System.out.println("====================");
        model.addAttribute("lId",lId);
        return "login1";
    }

    //通过lId和密码进行登录
    @RequestMapping("/login")
    public String login(@ModelAttribute  Login login, String captcha, HttpSession session, Model model) {
        String simpleCaptcha = String.valueOf(session.getAttribute("simpleCaptcha"));
        System.out.println(simpleCaptcha);
        System.out.println("-----------------");
        System.out.println("login:"+login);
        if (captcha.equals(simpleCaptcha)) {
            System.out.println("..............");
            //开始登录验证
            Login currentLogin=loginService.loginByLId(login);
            System.out.println("currentLogin:"+currentLogin);
            if (currentLogin != null){
                int rid=currentLogin.getrId();
                if (rid==3) { //如果登录成功，将当前的登陆的人，记录在会话中
                    System.out.println("+++++++++++");
                    session.setAttribute("currentLogin", currentLogin);
                    return "redirect:/underindex.action";

                } else if(rid==2){
                    session.setAttribute("currentLogin", currentLogin);
                    return "forward:/home.jsp";

                }else if (rid==1){
                    session.setAttribute("currentLogin", currentLogin);
                    return "forward:/home.jsp";
                }
                else {
                    //用户编号或密码错误
                    model.addAttribute("mess", "用户lid或密码有误，请重新输入");
                    return "login1";
                }

            } else {
                model.addAttribute("mess", "用户lid或密码有误，请重新输入");
                return "login1";
            }

        }else {
            model.addAttribute("mess", "验证码错误，请重新输入");
            return "login1";
        }
    }
    //进入修改用户密码页面
    @RequestMapping("/toresetpass")
    public String toresetpass(){
        return "updateLogin";
    }

    //修改密码控制器
    @RequestMapping("/resetpass")
    public String resetpass(@ModelAttribute Login login ,String lPass1){
        Login currentlogin=loginService.loginByLId(login);

        if (currentlogin==null){
            return "updateLogin";
        }else{
            System.out.println(lPass1);
            login.setlPass(lPass1);
            boolean flag=loginService.updatePass(login);
            if (flag){
                return "redirect:/tologin1.action";
            }else {
                return "updateLogin";
            }
        }
    }

    //验证码控制器
    @RequestMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) {
        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");

            OutputStream os = response.getOutputStream();
            // 返回验证码和图片的map
            Map<String, Object> map = Captcha.getImageCode(86, 37, os);
            String simpleCaptcha = "simpleCaptcha";
            session.setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
            session.setAttribute("codeTime", new Date().getTime());
            ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户注销
     * @param session
     * @return
     */
    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        return "login1";
    }

    /**
     * 个人中心
     * @return
     */
    @RequestMapping("/tousernav")
    public String usernav(){
        return "userNav";
    }

    /**
     * 个人信息展示
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/touserinfo")
    public String touserinfo(HttpSession session,Model model){
        Login login=(Login)session.getAttribute("currentLogin");
        int lId=login.getlId();
        User user=userService.findById(lId);
        model.addAttribute("userinfo",user);
        return "userInfo";
    }

    /**
     * 个人信息添加页面
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/touseradd")
    public String touseradd(@ModelAttribute User user,Model model){
        model.addAttribute("useradd",user);
        return "userAdd";
    }

    @RequestMapping("/useradd")
    public String useradd(@ModelAttribute User user){
        System.out.println(user.getBirthday());
        System.out.println(user.toString());
        boolean flag=userService.update(user);
        System.out.println(flag);
        return "redirect:/touserinfo.action";
    }
}
